﻿using System.Linq;
using System.Web.Mvc;
using pbvs.Models;
using pbvs.Models.ViewModels;
using pbvs.Data;
using pbvs.Data.Repositories.Interfaces;
using pbvs.Data.Repositories.RepositoryExtensions;
using pbvs.Services.Interfaces;
using System.Collections.Generic;

namespace pbvs.Services
{
	public class FormElementService : IFormElementService
	{
        private readonly IFormElementRepository _db;

        public FormElementService(IFormElementRepository db)
		{
			_db = db;
		}

		public FormElementViewModel LoadViewModel(string field)
		{
			FormElementViewModel vm = new FormElementViewModel ();
            vm.Elements = _db.Elements.ByField(field).OrderBy(f => f.Field);
            IList<SelectListItem> dropDownItems = new List<SelectListItem>();
            foreach (FormElement elem in vm.Elements)
            {
                SelectListItem item = new SelectListItem
                {
                    Text = elem.Field,
                    Value = elem.Field
                };
                dropDownItems.Add(item);
            }
            dropDownItems.Insert(0, new SelectListItem { Value = "Select One", Text = "0" });
            vm.ElementsDropDown = new SelectList(dropDownItems, "Text", "Value", field);
            
            if (!string.IsNullOrEmpty(field))
            {
                FormElement elem = _db.Elements.ByField(field).First();
                vm.Field = elem.Field;
                vm.HelpText = elem.HelpText;
            }
			return vm;
		}

		public void SaveFormElement(FormElement elem)
		{
			if (_db.Elements.Any(f => f.Field == elem.Field))
			{
                FormElement dbElem = _db.Elements.ByField(elem.Field).First();
				dbElem.HelpText = elem.HelpText;
                _db.Update(elem);
			}
			else
			{
				_db.Add(elem);
			}
			_db.Save();
		}
	}
}